#include "ByteBuffer.h"
#include <assert.h>
#include <string.h>

ByteBuffer::ByteBuffer() :
		_size(64), _length(0), _buffer(NULL) {
	resize(_size);
}

ByteBuffer::ByteBuffer(size_t init_size) :
		_size(init_size), _length(0), _buffer(NULL) {
	resize(_size);
}

ByteBuffer::~ByteBuffer() {
	delete _buffer;
}

void ByteBuffer::resize(size_t newsize) {
	assert(newsize > 0);
	if (_size < newsize) {
		_buffer = new char[newsize];
		if (_buffer != NULL) {
			_size = newsize;
			clear();
		}
	}
}

void ByteBuffer::clear() {
	if (_buffer != NULL) {
		memset(_buffer, 0, _size);
		_length = 0;
	}
}

size_t ByteBuffer::append(char* data, size_t size) {
	if (_length + size > _size) {
		char* oldbuf = _buffer;
		size_t oldlen = _length;
		resize(_length + size);
		if (oldbuf != NULL && _buffer != NULL) {
			memcpy(_buffer, oldbuf, oldlen);
			_length = oldlen;
		}
	}

	if (_buffer != NULL) {
		memcpy(_buffer + _length, data, size);
		_length += size;
	}

	return _length;
}
